import React from 'react';
import {Select} from "antd";
import {SelectProps, SelectValue} from 'antd/lib/select';
import useDicListByCategoryCode from "@/hooks/useDicListByCategoryCode";
import {DicValueType} from "@/global";
import {convertDicValueByType} from "@/utils/utils";

const {Option} = Select;

export interface DicSelectProps extends SelectProps<SelectValue> {
  /** 字典编码 */
  dicCode: string;
  /** 字典值类型 */
  dicValueType?: DicValueType;
  /** 是否添加全部选项 */
  showAll?: boolean;
  /** 全部选项值,默认为空字符串 */
  allValue?: string;
  /** 全部选项文本,默认为[全部] */
  allText?: string;
}

/**
 * 数据字段组件-下拉菜单展示
 */
const DicSelect = function (props: DicSelectProps) {
  const {dicCode, dicValueType = DicValueType.string, showAll, allValue, allText, ...rest} = props;
  const dicList = useDicListByCategoryCode(dicCode);

  return (
    <Select
      {...rest}
    >
      {showAll && (<Option key="all" value={allValue || ''}>{allText}</Option>)}
      {dicList.map(p => <Option key={p.id} value={convertDicValueByType(p.value, dicValueType)}>{p.name}</Option>)}
    </Select>
  );
};

DicSelect.defaultProps = {
  showAll: false,
  dicValueType: DicValueType.string,
  allValue: '',
  allText: '全部'
};

export default React.memo(DicSelect);

